package com.suneast.suneaststore.modules.common;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;

import com.suneast.suneaststore.App;
import com.suneast.suneaststore.R;
import com.suneast.suneaststore.ui.fragments.BaseFragment;

import butterknife.BindView;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class NavigationFragment extends BaseFragment {
    private final static String TAG = NavigationFragment.class.getSimpleName();

    private final static String key = "33DBZ-27KRX-5YY4G-TRXS7-IRQWH-BSBHO";
    private final static String baseurl = "http://apis.map.qq.com/tools/";

    private String desLongitude, desLatitude, desName, desAddr;
    private String keyword;
    private int radius;
    private int methodId;

    @BindView(R.id.title_bar)
    TextView title;

    @OnClick(R.id.ib_return_back)
    void onBackPressed() {
        pop();
    }

    @OnClick(R.id.ib_backward)
    void onBackward() {
        navigationView.goBack();
    }

    @OnClick(R.id.ib_refresh)
    void onRefresh() {
        navigationView.reload();
    }

    @NeedsPermission({ Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION })
    void dummyRequestPermissions() {
    }

    public NavigationFragment navigate(String longitude, String latitude, String name, String addr) {
        methodId = 0;
        desLatitude = latitude;
        desLongitude = longitude;
        desName = name;
        desAddr = addr;
        return this;
    }

    // 按坐标中心圆形搜，后续可以加矩形和在城市内搜
    public NavigationFragment search(String longitude, String latitude, String keyword, int radius) {
        methodId = 1;
        desLatitude = latitude;
        desLongitude = longitude;
        this.keyword = keyword;
        this.radius = radius;
        return this;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        NavigationFragmentPermissionsDispatcher.dummyRequestPermissionsWithPermissionCheck(this);
    }

    @Override
    public int setLayout() {
        return R.layout.fragment_navigation;
    }

    @BindView(R.id.navigation_view)
    WebView navigationView;

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        title.setText(R.string.navigation);
        navigationView.setWebChromeClient(new WebChromeClient() {
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
            }
        });
        navigationView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                android.util.Log.d(TAG, "URL=" + url);
                if (url.startsWith("http:") || url.startsWith("https:")) {
                    view.loadUrl(url);
                } else {
                    try {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Toast.makeText(NavigationFragment.this.getContext(), "请安装腾讯手机地图以获取更好的体验", Toast.LENGTH_SHORT).show();
                    }
                }
                return true;
            }
        });
        navigationView.loadUrl(getUrl());
        navigationView.getSettings().setJavaScriptEnabled(true);
        navigationView.getSettings().setGeolocationDatabasePath( getContext().getFilesDir().getPath() );
    }

    // 0 位置传入 1 位置检索
    private String getUrl() {
        StringBuilder builder = new StringBuilder(baseurl);
        builder.append("poimarker?type=").append(methodId);
        if (methodId == 0) {
            builder.append("&marker=coord:")
                    .append(desLatitude)
                    .append(",")
                    .append(desLongitude)
                    .append(";title:")
                    .append(desName)
                    .append(";addr:")
                    .append(desAddr)
                    .append("&key=")
                    .append(key)
                    .append("&referer=")
                    .append(App.getName());
        } else {
            builder.append("&keyword=")
                    .append(keyword)
                    .append("&center=")
                    .append(desLatitude)
                    .append(",")
                    .append(desLongitude)
                    .append("&radius=")
                    .append(radius)
                    .append("&key=")
                    .append(key)
                    .append("&referer=")
                    .append(App.getName());
        }
        android.util.Log.d(TAG, "URL=" + builder.toString());
        return builder.toString();
    }

    @OnShowRationale({ Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION })
    void showRationaleForCamera(final PermissionRequest request) {
        Context context = getContext();
        if (context != null) {
            new AlertDialog.Builder(getContext())
                    .setMessage(R.string.permission_location_rationale)
                    .setPositiveButton(R.string.text_allow, (dialog, button) -> request.proceed())
                    .setNegativeButton(R.string.text_deny, (dialog, button) -> request.cancel())
                    .show();
        }
    }
}
